package gw.com.android.ui.trade.Fragment;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONException;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.TradePresenter;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.ui.trade.TradeOrderActivity;
import gw.com.android.ui.trade.TradeProductPopWindow;
import gw.com.android.ui.trade.TradeRangeModel;
import gw.com.android.ui.views.NumericEdit;
import gw.com.android.ui.views.OrderBottomView;
import gw.com.android.ui.views.TitleRangeView;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;
import www.com.library.view.NumberInput;

/**
 * 市价下单fragment界面
 *
 * @author Reeta.zou
 *
 */
public class MarketOrderFragment extends BaseOrderFragment {

	@BindView(R.id.morder_title_deviation)
	TitleRangeView mRangeTitleView;
	@BindView(R.id.morder_title_lot)
	TitleRangeView mLotTitleView;
	/**产品列表视图*/
	@BindView(R.id.proNameLayout)
	View mPrdNameLayout;
	/** 产品列表 */
	@BindView(R.id.proNameView)
	TextView mPrdNameView;
	/** 手数加减器 */
	@BindView(R.id.morder_input_lot)
	NumericEdit m_lotEditView = null;
	/** 最大偏移加减器 */
	@BindView(R.id.morder_input_deviation)
	NumericEdit m_deviationEditView = null;
	/** 保证金 */
	@BindView(R.id.margin_view)
	TextView mMarginView;

	/**产品弹层*/
	private TradeProductPopWindow mProPopwindow = null;

	/** 当前买卖价格 */
	private double mCurPrice = 0.0;
	/** 偏移量默认值 */
	private String mCurRange = "";
	/**保证金逻辑处理对象*/
	private TradePresenter mPresenter;

	/**
	 * 更新通知处理
	 */
	private Handler HandlerCallback = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GTSConst.REPLY_SYMBOL_TICK_UPDATE:
				// 更新界面价格和范围值
				mBottomview.updateProduct(mRangeModel);
				updateWithPrice();
				onConfigDynamicViews();
				checkError();
				break;
			case GTSConst.REPLY_SYMBOL_UPDATE:
				if(null != mProPopwindow){
					mProPopwindow.refreshData();
				}
				if(null != m_lotEditView){
					setMarginView(m_lotEditView.getFloatValue());
				}
				break;
			}
		}
	};

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		if (args != null) {
			int zoneType = args.getInt("zoneType");
			mUiCode = args.getInt("uiCode");
			mTickModel = DataManager.instance().getTickModel(mUiCode);
			mTradeDir = args.getInt("orderDir", AppContances.TRADE_TYPE_BUY);
			if(null == mTickModel){
				if (null != getActivity()) {
					getActivity().finish();
				}
				Logger.e("mTickModel对象为空，出现异常");
				return;
			}
			setProductInfo();
		}
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_order_create_market;
	}


	/**
	 * 初始化界面控件元素，参数设置
	 */
	@Override
	protected void initLayoutView() {
		super.initLayoutView();
		mPrdNameLayout.setSelected(false);

		if (mTradeDir == AppContances.TRADE_TYPE_BUY) {
			m_buyLayout.setSelected(true);
			m_sellLayout.setSelected(false);
		} else {
			m_buyLayout.setSelected(false);
			m_sellLayout.setSelected(true);
		}

		m_deviationEditView.setLongClickable(false);
		m_lotEditView.setLongClickable(false);
		m_deviationEditView.setAfterTextChangedListener(mTextChangedListener);
		m_lotEditView.setAfterTextChangedListener(mTextChangedListener);
		m_lotEditView.getNumericInput().setOnFocusChangeListener(this);
		m_deviationEditView.getNumericInput().setOnFocusChangeListener(this);

		mBottomview.setPriceType(false);
		mBottomview.setFoldView(false);
		mBottomview.setFocusChange(this);
		mBottomview.setErrorCheckLisenter(new OrderBottomView.onErrorCheckLisenter() {

			@Override
			public void onErrorCheck() {
				checkError();
			}
		});
		mRangeTitleView.setTitleView(R.string.order_title_deviation);
		mLotTitleView.setTitleView(R.string.order_title_lot);

		cmd = AppContances.ORDER_TYPE_MARKET;
		mRangeModel = new TradeRangeModel();
		mPresenter = new TradePresenter(mUiCode);
	}

	@Override
	protected void initViewData() {
		mPrdNameView.setText(mSymbol);
		updateWithPrice();
		TradeBusiness.calLossAndWin(mTickModel,mSymbolModel,mRangeModel,mTradeDir);
		mBottomview.setProductInfo(mRangeModel);
		onConfigDynamicViews();
		m_deviationEditView.setText(mCurRange);
		m_lotEditView.setText(DoubleConverter.toStringData(mCurLot, 2));
	}

	private void setProductInfo(){
		if(null != TradeOrderActivity.mInstance){
			TradeOrderActivity.mInstance.mUiCode = mTickModel.getInt(GTSConst.JSON_KEY_CODEID);
		}
		mSymbol = DataManager.instance().getPrdName(mTickModel);
		mUiCode = mTickModel.getInt(GTSConst.JSON_KEY_CODEID);
		zoneId = mTickModel.getInt(GTSConst.JSON_KEY_ZONE);
		updateSymbolModel();
		mCurLot = GTConfig.instance().getProductOrderLot(mUiCode,mSymbolModel.getString(GTSConst.JSON_KEY_DEFAULTOT));
		mCurRange = GTConfig.instance().getProductRange(mUiCode, mSymbolModel.getString(GTSConst.JSON_KEY_RANGE));
	}

	@Override
	public void registerRxBus() {
		Disposable marginRegister = RxBus.getInstance().register(GTSConst.REPLY_MARGIN_UPDATE+"", Bundle.class).observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Consumer<Bundle>(){

					@Override
					public void accept(@NonNull Bundle bundle) throws Exception {
						if(null != bundle){
							onMarginNotify(bundle.getInt("iNotification"));
						}
					}
				});

		bindSubscription(marginRegister);

		Disposable positionListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_POSTION_LIST+"", Bundle.class).observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Consumer<Bundle>(){

					@Override
					public void accept(@NonNull Bundle bundle) throws Exception {
						if(null != mPresenter){
							setMarginView(m_lotEditView.getFloatValue());
						}
					}
				});
		bindSubscription(positionListRegister);

	}

	/**
	 * 切换产品
	 *
	 */
	private void changeProduct(DataItemDetail tickModel) {
		if(null != tickModel){
			mTickModel = tickModel;
			AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(mTickModel.getInt(GTSConst.JSON_KEY_CODEID)));
			setProductInfo();
			initViewData();
			if(null != mPresenter){
				mPresenter.setMarginLevel(mUiCode);
				setMarginView(m_lotEditView.getFloatValue());
			}
		}
	}


	/**
	 * 设置界面加减器中各属性值
	 *
	 */
	private void onConfigDynamicViews() {
		// 设置手数
		m_lotEditView.setMax(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMAX)));
		m_lotEditView.setMin(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN)));
		m_lotEditView.setMinSteps(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESSTEP)));
		m_lotEditView.setDigits(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMAX));
		mLotTitleView.setRangeView(AppMain.getAppString(R.string.order_hint_lot, mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN)), AppMain.getAppString(R.string.order_hint_lot, mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMAX)));

		// 设置成交范围
		m_deviationEditView.setMin(0);
		m_deviationEditView.setMax(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_RANGE)));
		m_deviationEditView.setMinSteps(1);
		m_deviationEditView.setDigits(mSymbolModel.getString(GTSConst.JSON_KEY_RANGE).length(), mSymbolModel.getString(GTSConst.JSON_KEY_RANGE).length(), 0);
		mRangeTitleView.setRangeView("0", mSymbolModel.getString(GTSConst.JSON_KEY_RANGE)+"");
	}

	/**
	 * 显示选择产品pop
	 */
	private void showProPop() {
		if (null == mProPopwindow) {
			mProPopwindow = new TradeProductPopWindow(getActivity(), mPrdNameLayout, AppMain.getAppString(R.string.order_product), mUiCode, zoneId, new TradeProductPopWindow.RecyclerItemClickListener() {
				@Override
				public void onClick(DataItemDetail model) {
					mPrdNameLayout.setSelected(false);
					changeProduct(model);
				}
			});
			mProPopwindow.popWindow.setBackgroundDrawable(new BitmapDrawable(AppMain.getApp().getResources(), (Bitmap) null));
		}
		mProPopwindow.show();
	}

	/**
	 * 设置初始保证金值
	 * @param lot
     */
	private void setMarginView(float lot){
		if(null != mMarginView && null != mSymbolModel && null != mPresenter){
			mMarginView.setText(mPresenter.calLevelMargin(lot, DoubleConverter.toFloatData(mSymbolModel.getString(GTSConst.JSON_KEY_MARGININITIAL)), mTradeDir));
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			if (null != TradeOrderActivity.mInstance && TradeOrderActivity.mInstance.hasChangeLot) {
				mCurLot = GTConfig.instance().getProductOrderLot(mUiCode, mSymbolModel.getString(GTSConst.JSON_KEY_DEFAULTOT));
				if (null != m_lotEditView) {
					m_lotEditView.setText(DoubleConverter.toStringData(mCurLot, 2));
				}
			}

			if (null != TradeOrderActivity.mInstance && TradeOrderActivity.mInstance.hasChangeRange) {
				mCurRange = GTConfig.instance().getProductRange(mUiCode, mSymbolModel.getString(GTSConst.JSON_KEY_RANGE) + "");
				if (null != m_deviationEditView) {
					m_deviationEditView.setText(mCurRange);
				}
			}

			if (null != TradeOrderActivity.mInstance && mUiCode != TradeOrderActivity.mInstance.mUiCode) {
				mUiCode = TradeOrderActivity.mInstance.mUiCode;
				if(null != mProPopwindow){
					mProPopwindow.refreshData(mUiCode);
				}
				DataItemDetail mData = DataManager.instance().getTickModel(mUiCode);
				changeProduct(mData);
			}

			if (null != TradeOrderActivity.mInstance && mTradeDir != TradeOrderActivity.mInstance.mTradeDir) {
				changeTradeDir(TradeOrderActivity.mInstance.mTradeDir);
			}

			checkError();
		}
	}

	/**
	 * 输入框文本变化处理
	 */
	private final NumberInput.OnTextChangedListener mTextChangedListener = new NumberInput.OnTextChangedListener() {
		@Override
		public void onTextChanged(EditText edit, Editable s) {
			if(edit == m_lotEditView.getNumericInput()){
				setMarginView(m_lotEditView.getNumericInput().getFloatValue());
			}
			checkError();
		}
	};

	/**
	 * 焦点变化
	 * @param v
	 * @param hasFocus
     */
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		mBottomview.onFocusChanged(v, hasFocus);
		//处理最大偏移为空情况下，离开焦点默认设置为0
		if (v == m_deviationEditView.getNumericInput()) {
			m_deviationEditView.getNumericInput().setText(
					m_deviationEditView.getNumericInput().getValueString());
		}
		checkError();
	}

	/**
	 * 检查界面错误
	 * @return
	 */
	private boolean checkError() {
		String errorMessage = "";
		boolean result = false;

		//偏移量
		String rangePrice = m_deviationEditView.getText();
		String errorMessage1 = TradeBusiness.getRangeErrorMsg(mSymbolModel.getString(GTSConst.JSON_KEY_RANGE), rangePrice);
		if (!"".equals(errorMessage1)) {
			mRangeTitleView.setErrorColor();
			errorMessage = errorMessage1;
		}else{
			mRangeTitleView.setDefalutColor();
		}

		//手数
		String lot = m_lotEditView.getText();
		String errorMessage2 = TradeBusiness.getLotErrorMsg(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN),
				mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMAX), mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESSTEP), lot);
		if (!"".equals(errorMessage2)) {
			mLotTitleView.setErrorColor();
			if("".equals(errorMessage)){
				errorMessage = errorMessage2;
			}
		}else{
			mLotTitleView.setDefalutColor();
		}

		//检查止损止盈
		String errorMessage3 = mBottomview.checkError();
		if (!"".equals(errorMessage3) && "".equals(errorMessage)) {
			errorMessage = errorMessage3;
		}

		if (isVisible() && null != mStatusListener) {
			mStatusListener.onError(errorMessage);
		}

		if(!"".equals(errorMessage)) {
			return true;
		}else {
			return false;
		}
	}

	@OnClick(R.id.sell_price_layout)
	void changeSellDir(){
		changeTradeDir(AppContances.TRADE_TYPE_SALE);
	}

	@OnClick(R.id.buy_price_layout)
	void changeBuyDir(){
		changeTradeDir(AppContances.TRADE_TYPE_BUY);
	}

	/**
	 * 买卖方向切换
	 *
	 * @param tradeDir
	 */
	private void changeTradeDir(int tradeDir) {
		mTradeDir = tradeDir;
		if(null != TradeOrderActivity.mInstance ){
			TradeOrderActivity.mInstance.mTradeDir = tradeDir;
		}
		if (mTradeDir == AppContances.TRADE_TYPE_SALE) {
			m_buyLayout.setSelected(false);
			m_sellLayout.setSelected(true);
		} else {
			m_buyLayout.setSelected(true);
			m_sellLayout.setSelected(false);
		}
		TradeBusiness.calLossAndWin(mTickModel,mSymbolModel,mRangeModel,mTradeDir);
		mBottomview.setProductInfo(mRangeModel);
		setMarginView(m_lotEditView.getFloatValue());
		MobclickEventUtlis.MobclickEventByAccountType(getActivity(),"changeTradeDir"+mTradeDir);
	}

	@OnClick(R.id.proNameView)
	void selectProduct(){
		//isSelected标识之前的状态，之前为true收起来，之前为false展开
		if (mPrdNameLayout.isSelected()) {
			mPrdNameLayout.setSelected(false);
			if (null != mProPopwindow) {
				mProPopwindow.hidden();
			}
		} else {
			mPrdNameLayout.setSelected(true);
			showProPop();
		}
	}

	/**
	 * 市价开仓前各种条件判断
	 *
	 * @return
	 */
	public boolean hasPostData() {
		if (checkError()) {
			return false;
		}

		String errorMessage = "";
		// 不判断是否超过持仓张数（持仓+挂单）100
		// errorMessage = TradeCheck.getMoreNumErrorMsg(false);
//		if ("".equals(errorMessage)) {
//			errorMessage = TradeCheck.getMoreLotErrorMsg(mProduct,
//					m_lotEditView.getText());
//		}
		if (!"".equals(errorMessage)) {
			PopupConfirmDialog.NotifyPrompt(getActivity(), errorMessage);
			return false;
		}

		if (!TradeBusiness.PreOrderCheck(getActivity(), mTickModel.getInt(GTSConst.JSON_KEY_ZONE), mTickModel.getInt(GTSConst.JSON_KEY_TRADESTATE), true)) {
			return false;
		}

		try {
			jsonData.put(GTSConst.JSON_KEY_CODEID, mUiCode);
			jsonData.put(GTSConst.JSON_KEY_DIRECTION, mTradeDir);
			if (mTradeDir == AppContances.TRADE_TYPE_BUY){
				jsonData.put(GTSConst.JSON_KEY_ORDERPRICE, mTickModel.getString(GTSConst.JSON_KEY_BUYPRICE));
			}else{
				jsonData.put(GTSConst.JSON_KEY_ORDERPRICE, mTickModel.getString(GTSConst.JSON_KEY_SELLPRICE));
			}

			mSeq = GTSDataListener.curSeq++;
			GTSDataListener.instance().addSeqList(mSeq+"", cmd+"");
			Logger.e("市价开仓下单的seq == " + mSeq);
			jsonData.put(GTSConst.JSON_KEY_EXPIRETYPE, AppContances.VALID_TYPE_DAY);
			jsonData.put(GTSConst.JSON_KEY_VOLUME, DoubleConverter.toStringData(m_lotEditView.getText(), 2));
			jsonData.put(GTSConst.JSON_KEY_RANGE, m_deviationEditView.getText());
			jsonData.put(GTSConst.JSON_KEY_ORDERTYPE, AppContances.ORDER_TYPE_MARKET_TYPE);
			jsonData.put(GTSConst.JSON_KEY_USEDIP, 0);
			jsonData.put(GTSConst.JSON_KEY_STOPLOSS, mBottomview.getLossPrice());
			jsonData.put(GTSConst.JSON_KEY_STOPPROFIT, mBottomview.getWinPrice());
			jsonData.put(GTSConst.JSON_KEY_TRADE_SEQ, mSeq);
		}catch (JSONException e){
			e.printStackTrace();
		}
		mDetail.setStringValue("mCurrentTag", AppContances.TAB_ID_CREATE_ORDER);
		mDetail.setStringValue("mSymbol", mSymbol);
		mDetail.setIntValue("mPrdCode", mUiCode);
		mDetail.setIntValue("mTradeDir", mTradeDir);
		mDetail.setIntValue("rangePrice", m_deviationEditView.getIntValue());
		mDetail.setStringValue("mCurLot", jsonData.optString(GTSConst.JSON_KEY_VOLUME));
		mDetail.setStringValue("mPrice", jsonData.optString(GTSConst.JSON_KEY_OPENPRICE));

		return true;
	}

	@Override
	public void requstData() {
        int result = AppTerminal.instance().reqOrder(cmd, jsonData.toString());
		if(result != 0){
			if(null != mStatusListener){
				mStatusListener.onFail();
			}
			PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1016));
		}
	}

	@Override
	public void onSymbolNotify(DataItemDetail tickModel) {
		super.onSymbolNotify(tickModel);
		if(null != tickModel){
			if(mUiCode == tickModel.getInt(GTSConst.JSON_KEY_CODEID)){
				mTickModel = tickModel;
//				Logger.e("onSymbolNotify TICK == " + mSymbolModel.getString(GTSConst.JSON_KEY_MINPRICE)+", " + mTickModel.getString(GTSConst.JSON_KEY_BUYPRICE));
				if(null != mRangeModel){
					TradeBusiness.calLossAndWin(mTickModel,mSymbolModel,mRangeModel,mTradeDir);
					HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
				}
			}else{
				if(null != mPresenter){
					setMarginView(m_lotEditView.getFloatValue());
				}
			}
		}
	}

	@Override
	public void onSymbolNotify() {
		super.onSymbolNotify();
		updateSymbolModel();
		HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_UPDATE);
	}

	@Override
	public void onMarginNotify(int mSwitch) {
		if(null != mPresenter){
			mPresenter.setMarginLevel(mUiCode);
			setMarginView(m_lotEditView.getFloatValue());
		}
	}

	@Override
	public void onOrderSuccessNotify(int notifyId, int orderId, DataItemDetail model) {
		if (mSeq == notifyId) {
			Logger.e("下单成功后  orderId = " + orderId + " mSeq == " + mSeq);
			if (null != model) {
				mDetail.setIntValue("mOrderID", orderId);
				mDetail.setStringValue("mPrice",model.getString(GTSConst.JSON_KEY_OPENPRICE));
				mDetail.setStringValue("mTime", StringFormatter.instance().secToDateTime(model.getInt(GTSConst.JSON_KEY_TIME)));
				if (!DoubleConverter.isZero(DoubleConverter.toFloatData(model.getString(GTSConst.JSON_KEY_STOPLOSS)))) {
					mDetail.setStringValue("mLoss", model.getString(GTSConst.JSON_KEY_STOPLOSS));
				} else {
					mDetail.setStringValue("mLoss", "");
				}
				if (!DoubleConverter.isZero(DoubleConverter.toFloatData(model.getString(GTSConst.JSON_KEY_STOPPROFIT)))) {
					mDetail.setStringValue("mWin",model.getString(GTSConst.JSON_KEY_STOPPROFIT));
				} else {
					mDetail.setStringValue("mWin", "");
				}

				if (null != mStatusListener) {
					Logger.e("onOrderSuccessNotify mStatusListener 下单成功后  orderId = "
							+ orderId);
					mStatusListener.onSuc(mDetail);
				}
			}
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		if(null != mProPopwindow){
			mProPopwindow.hidden();
		}
	}
}